package com.ysy.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class ThreadPoolConfig {

    private static final int coreSize = 10;

    private static final int coreMaxSize = 10;

    private static final int queueSize = 100;

    public static final String NOTE_EXECUTOR = "noteExecutor";

    /**
     *
     * 获取核心数
     * int cores = Runtime.getRuntime().availableProcessors();
     * System.out.println("系统CPU核心数: " + cores);
     * executor.setWaitForTasksToCompleteOnShutdown(true);
     * @return ThreadPoolTaskExecutor
     */
    @Bean(name = NOTE_EXECUTOR)
    @Primary
    public ThreadPoolTaskExecutor threadPoolTaskExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(coreSize);
        executor.setMaxPoolSize(coreMaxSize);
        executor.setQueueCapacity(queueSize);
        executor.setThreadNamePrefix("note-executor-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
       // executor.setThreadFactory(new MyThreadFactory());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 设置等待时间，超过这个时间还没有销毁就强制销毁
        // 确保应用最后能够关闭，而不是被没有完成的任务阻塞等待
        executor.setAwaitTerminationSeconds(60);
        executor.initialize();
        return executor;
    }




}
